import java.util.PriorityQueue;
class MyTimerTask implements Comparable<MyTimerTask>{
    private long time;
    private Runnable runnable;
    public MyTimerTask(Runnable runnable, long delay){
        this.time=delay+System.currentTimeMillis();
        this.runnable=runnable;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time-o.time);
    }

    public void run(){
        runnable.run();
    }
    public long getTime(){
        return time;
    }
}

class MyTimer {
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private Object lock=new Object();

    public MyTimer() {

        Thread t = new Thread(() -> {
            while (true) {
                synchronized (lock) {
                    while (queue.isEmpty()) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    MyTimerTask current = queue.peek();
                    if (System.currentTimeMillis() >= current.getTime()) {
                        //要执行任务
                        current.run();
                        queue.poll();
                    } else {
                        try {
                            lock.wait(current.getTime()-System.currentTimeMillis());
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        });
        t.start();
    }

    public void schedule(Runnable runnable, long delay) {
        synchronized ( lock) {
            MyTimerTask myTimerTask = new MyTimerTask(runnable, delay);
            queue.offer(myTimerTask);
            lock.notify();

        }
    }
}

public class Demo1 {
    public static void main(String[] args) {
        MyTimer myTimer=new MyTimer();
        myTimer.schedule(()->{
            System.out.println("Hello 3000");
        },3000);
        myTimer.schedule(()->{
            System.out.println("Hello 2000");
        },2000);
    }
}
